package com.qing.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock锁，jvm将花费较少的时间来调度线程，性能更好，也具有更好的扩展性
 */
public class Lock {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        // new Thread(buyTicket, "A").start();
        // new Thread(buyTicket, "B").start();
        // new Thread(buyTicket, "C").start();
        Thread t1 = new Thread(buyTicket,"T1");
        Thread t2 = new Thread(buyTicket,"T2");
        Thread t3 = new Thread(buyTicket,"T3");
        t1.setPriority(1);
        t1.start();
        t2.setPriority(2);
        t2.start();
        t3.setPriority(10);
        t3.start();
    }

}

class BuyTicket implements Runnable {

    int ticket = 10;
    boolean flag = true;

    //定义Lock锁
    private final ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        while (flag) {
            try {
                isBuy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void isBuy() throws InterruptedException {
        try {
            reentrantLock.lock();
            if (ticket <= 0) {
                flag = false;
                return;
            }
            System.out.println(Thread.currentThread().getName() + "买到了第" + (ticket--) + "张票");
        } finally {
            reentrantLock.unlock();
        }
    }
}
